package input_output;

import java.util.Timer;
import java.util.TimerTask;

import messageHandler.MessageHandler;

import org.apache.log4j.Logger;

import simulators.MessageInbox;
import types.TextMessage;

import config.ConfigData;

public class InboxMonitor
{
    private static Logger myLogger = Logger.getLogger(InboxMonitor.class.getName());
    Timer timer;
    
    /**
     * Constructor
     */
    public InboxMonitor()
    {
	timer = new Timer("Inbox Monitor");
    }
    
    /**
     * Timer thread checks the inbox for messages
     */
    public void monitor()
    {
	myLogger.info("Running in inbox monitor every " + ConfigData.getMonitorRate() + " ms.");
	    
	// Schedule a timer at a fixed rate
	timer.scheduleAtFixedRate(new TimerTask()
	{
	    public void run()
	    {
		// Real mode
		if (!ConfigData.isTestMode()) 
		{
		    // Fill in later
		}
		// Test Mode
		else 
		{		    
		    TextMessage tm = MessageInbox.getMessage();
		    
		    while (null != tm)
		    {
			// Got message
			myLogger.info("Received message in inbox: " + tm);
			
			// Do something with it
			doStuffWithTextMessage(tm);
			
			// get another message
			tm = MessageInbox.getMessage();
		    }	    
		}
	    }
	}, 0, ConfigData.getMonitorRate());
    }
    
    /**
     * Stops the Timer thread from monitoring the inbox
     */
    public void stop()
    {
	myLogger.info("Stopping thread.");
	timer.cancel();
    }

    /**
     * Common method for testing and non-test to pass the message off
     */
    private void doStuffWithTextMessage(TextMessage tm)
    {
	MessageHandler.handleTextMessage(tm);
    }
}
